# 导入所需的库
import itchat
from itchat.content import TEXT, PICTURE, VIDEO, MAP, CARD, NOTE, SHARING, RECORDING, ATTACHMENT, FRIENDS, SYSTEM
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import os
import cv2
from PIL import Image
import numpy as np

# 登录微信
itchat.auto_login(hotReload=True)

# 获取好友列表
friends = itchat.get_friends(update=True)

# 将好友信息保存到文件中
with open('friends.txt', 'w') as f:
    for friend in friends:
        f.write(friend['NickName'] + ', ' + friend['Province'] + ', ' + friend['City'] + '\n')

# 给好友发送信息
@itchat.msg_register(TEXT)
def text_reply(msg):
    if msg['ToUserName'] == 'filehelper':
        # 如果是文件传输助手，则回复“收到文件，谢谢！”
        return '收到文件，谢谢！'
    else:
        # 否则，回复“收到信息，谢谢！”
        return '收到信息，谢谢！'

# 好友性别可视化
gender_count = {'男': 0, '女': 0, '未知': 0}
for friend in friends:
    gender_count[friend['Sex']] += 1
plt.figure(figsize=(8, 4))
plt.bar(gender_count.keys(), gender_count.values())
plt.title('好友性别分布')
plt.show()

# 好友所在省份可视化
province_count = {}
for friend in friends:
    province = friend['Province']
    if province not in province_count:
        province_count[province] = 0
    province_count[province] += 1
plt.figure(figsize=(10, 6))
plt.bar(province_count.keys(), province_count.values())
plt.title('好友所在省份分布')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 好友所在城市可视化
city_count = {}
for friend in friends:
    city = friend['City']
    if city not in city_count:
        city_count[city] = 0
    city_count[city] += 1
plt.figure(figsize=(10, 6))
plt.bar(city_count.keys(), city_count.values())
plt.title('好友所在城市分布')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 特殊好友可视化
special_friends = []
for friend in friends:
    if friend['RemarkName'] != '':
        special_friends.append(friend['RemarkName'])
plt.figure(figsize=(8, 4))
plt.hist(special_friends, bins=len(special_friends), color='skyblue', edgecolor='black')
plt.title('特殊好友数量')
plt.xlabel('好友备注名')
plt.ylabel('数量')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 签名词云化
signatures = [friend['Signature'] for friend in friends if friend['Signature'] != '']
signature_text = ' '.join(signatures)
wordcloud = WordCloud(font_path='simhei.ttf').generate(signature_text)
plt.figure(figsize=(10, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('签名词云')
plt.show()

# 好友头像集成
avatar_dir = 'avatars/'
if not os.path.exists(avatar_dir):
    os.mkdir(avatar_dir)
for friend in friends:
    avatar_url = friend['HeadImgUrl']
    avatar_name = avatar_dir + friend['UserName'] + '.jpg'
    if not os.path.exists(avatar_name):
        try:
            itchat.download_file(avatar_url, avatar_name)
        except Exception as e:
            print(f'下载头像失败：{e}')

# 人脸识别
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
for avatar_name in os.listdir(avatar_dir):
    img = cv2.imread(avatar_dir + avatar_name)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
    cv2.imshow('人脸识别', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 好友头像的分类和分析
# 这里可以根据需要添加代码来对头像进行分类和分析，例如统计每种类型的头像数量、制作头像集合等等

# 界面设计
# 由于界面设计需要使用到特定的库（如easggui或tkinter），这里无法提供完整的界面代码。
# 但是，你可以参考相关库的文档来创建一个简单的界面，用于展示上述功能。

# 打包exe
# 使用pyinstaller打包exe的命令如下：
# pyinstaller -F your_script.py
# 其中，your_script.py是你的Python脚本文件名。

